/* eslint-disable compat/compat */
import React, { useEffect, useState } from "react";
import type { GetProp, TableProps } from "antd";
import { Table, Card, message,Tag } from "antd";
import type { SorterResult } from "antd/es/table/interface";
import { TruckOrderLogVO, TruckOrderVo } from "../../types";
import { pageListTruckOrderLogs } from "@/services/order/order_api";
import { useIntl } from "@umijs/max";
import dayjs from 'dayjs';
import { formatToLocalTime } from '@/utils/time';

type ColumnsType<T extends object = object> = TableProps<T>["columns"];
type TablePaginationConfig = Exclude<
  GetProp<TableProps, "pagination">,
  boolean
>;

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: SorterResult<any>["field"];
  sortOrder?: SorterResult<any>["order"];
  filters?: Parameters<GetProp<TableProps, "onChange">>[1];
}

interface FormProps {
  data?: TruckOrderVo;
}

const LogListApp: React.FC<FormProps> = ({ data }) => {
  const intl = useIntl();
  const [dataSources, setDataSource] = useState<TruckOrderLogVO[]>([]);
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  useEffect( () => {
     queryDate(tableParams);
  }, [data]);

  const queryDate = async (params:any) => {
    if (!data?.orderCode) return;
    // console.log("queryDate", { data.orderCode, current, pageSize});
    try {
      setLoading(true);
      const pageParams = {
        current: params.pagination?.current,
        pageSize: params.pagination?.pageSize,
        orderCode: data?.orderCode,
      };

      const response = await pageListTruckOrderLogs(pageParams);
      if (response.code !== 0) {
        const errorMessage =
          response.msg || intl.formatMessage({ id: "request.error.default" });
        throw new Error(errorMessage);
      }

      setDataSource(
        Array.isArray(response.data.data) ? response.data.data : []
      );
      setTableParams((prev) => ({
        ...prev,
        pagination: {
          ...prev.pagination,
          total: response.data.total || 0,
        },
      }));
    } catch (error) {
      if (error instanceof Error) {
        message.error(error.message);
      } else {
        message.error(intl.formatMessage({ id: "request.error.unknown" }));
      }
    } finally {
      setLoading(false);
    }
  };

  const columns: ColumnsType<TruckOrderLogVO> = [
  {
    title: intl.formatMessage({ id: 'pages.log.columns.index' }),
    dataIndex: "index",
    width: 60,
    fixed: "left",
    align: "center",
    render: (_, __, index) => {
      const { current = 1, pageSize = 10 } = tableParams.pagination || {};
      return (current - 1) * pageSize + index + 1;
    },
  },
  {
    title: intl.formatMessage({ id: 'pages.log.columns.opType' }),
    dataIndex: "opType",
    key: "opType",
    width: 100,
    align: "center",
    fixed: "left",
  },
  {
    title: intl.formatMessage({ id: 'pages.log.columns.olType' }),
    dataIndex: "olType",
    key: "olType",
    width: 100,
    align: "center",
    render: (text) => {
      const map = {
        0: intl.formatMessage({ id: 'pages.log.types.status' }),
        1: intl.formatMessage({ id: 'pages.log.types.context' }),
        2: intl.formatMessage({ id: 'pages.log.types.fee' }),
      };
      return text in map ? map[text] : "-";
    },
  },
  {
    title: intl.formatMessage({ id: 'pages.log.columns.statusChange' }),
    dataIndex: "statusChange",
    key: "statusChange",
    width: 150,
    align: "center",
    render: (_, record) => {
      const statusMap = {
        1: {
          text: intl.formatMessage({ id: "pages.log.status.submitted" }),
          color: "blue",
        },
        2: {
          text: intl.formatMessage({ id: "pages.log.status.forecast" }),
          color: "green",
        },
        3: {
          text: intl.formatMessage({ id: "pages.log.status.cancelling" }),
          color: "orange",
        },
        4: {
          text: intl.formatMessage({ id: "pages.log.status.canceled" }),
          color: "red",
        },
        5: {
          text: intl.formatMessage({ id: "pages.log.status.pendingDelivery" }),
          color: "gold",
        },
        6: {
          text: intl.formatMessage({ id: "pages.log.status.inDelivery" }),
          color: "cyan",
        },
        7: {
          text: intl.formatMessage({ id: "pages.log.status.delivered" }),
          color: "green",
        },
        11: {
          text: intl.formatMessage({ id: "pages.log.status.abnormalForecast" }),
          color: "purple",
        },
        99: {
          text: intl.formatMessage({ id: "pages.log.status.obsolete" }),
          color: "gray",
        },
      };

      const fromStatus = statusMap[record.orderStatusFrom] || {
        text: record.orderStatusFrom || "-",
        color: "default",
      };
      const toStatus = statusMap[record.orderStatusTo] || {
        text: record.orderStatusTo || "-",
        color: "default",
      };

      return (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Tag color={fromStatus.color}>{fromStatus.text}</Tag>
          <span style={{ margin: "0 8px" }}>→</span>
          <Tag color={toStatus.color}>{toStatus.text}</Tag>
        </div>
      );
    },
  },
  {
    title: intl.formatMessage({ id: 'pages.log.columns.comments' }),
    dataIndex: "olComments",
    key: "olComments",
    width: 200,
  },
  {
    title: intl.formatMessage({ id: 'pages.log.columns.operator' }),
    dataIndex: "userName",
    key: "userName",
    width: 100,
    align: "center",     
  },
  {
    title: intl.formatMessage({ id: 'pages.log.columns.createTime' }),
    dataIndex: "createTime",
    key: "createTime",
    width: 160,
    align: "center",
    render: (text, record) => formatToLocalTime(record.createTime),
  },
];

  const handleTableChange: TableProps<TruckOrderLogVO>["onChange"] =async (
    pagination,
    filters,
    sorter
  ) => {
    const newParams = {
    pagination,
    filters,
    sortOrder: Array.isArray(sorter) ? undefined : sorter.order,
    sortField: Array.isArray(sorter) ? undefined : sorter.field,
  };
    setTableParams(newParams);
    await queryDate(newParams);
  };

  return (
    <Card>
      <Table<TruckOrderLogVO>
        columns={columns}
        rowKey={(record) => record.olId?.toString() || Math.random().toString()}
        dataSource={dataSources}
        pagination={{
          ...tableParams.pagination,
          showSizeChanger: true,
          pageSizeOptions: ["10", "20", "50", "100"],
        }}
        loading={loading}
        onChange={handleTableChange}
        scroll={{ x: 800 }}
      />
    </Card>
  );
};

export default LogListApp;
